/*
 * (C) Copyright 2015-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *   ohun@live.cn (夜色)
 */

package com.cn.server.websocket;

import com.cn.common.core.FastJsonUtils;
import com.cn.common.core.model.Request;
import com.cn.common.core.model.Result;
import com.cn.common.core.model.WebStockResponse;
import com.cn.common.core.session.Session;
import com.cn.server.msg.MessageHandler;
import com.cn.server.msg.PacketReceiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ohun on 2015/12/22.
 *
 * @author ohun@live.cn
 */
public final class WebSocketMessageDispatcher implements PacketReceiver {
    public static final int POLICY_REJECT = 2;
    public static final int POLICY_LOG = 1;
    public static final int POLICY_IGNORE = 0;
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketMessageDispatcher.class);
    private final Map<Short, Map<Short, MessageHandler>> handlers = new HashMap<>();
    private final int unsupportedPolicy;

    public WebSocketMessageDispatcher() {
        unsupportedPolicy = POLICY_REJECT;
    }

    public WebSocketMessageDispatcher(int unsupportedPolicy) {
        this.unsupportedPolicy = unsupportedPolicy;
    }

    public void register(Short module, Short cmd, MessageHandler handler) {
        Map<Short, MessageHandler> cmdMap = handlers.get(module);
        if (cmdMap == null) {
            cmdMap = new HashMap<>();
            handlers.put(module, cmdMap);
        }
        cmdMap.put(cmd, handler);
    }

    public MessageHandler unRegister(Short module, Short cmd) {
        Map<Short, MessageHandler> cmdMap = handlers.get(module);
        if (cmd == null) {
            return null;
        }
        return cmdMap.remove(cmd);
    }

    @Override
    public void onReceive(Request packet, Session session) {
        Map<Short, MessageHandler> cmdMap = handlers.get(packet.getModule());
        if (cmdMap == null) {
            LOGGER.error("no register module = {}", packet.getModule());
            return;
        }
        LOGGER.debug("当前type" + session.getType());
        WebStockResponse response = new WebStockResponse(packet);
        MessageHandler handler = cmdMap.get(packet.getCmd());
        if (handler != null) {
            Result<?> result = handler.handle(packet, session);
            //      //聊天每个消息都会返回对应的状态，比如发送成功或是失败等等
//                if (packet.getModule() == ModuleId.CHAT) {
//                    //聊天层数据在业务层已经发送
//                    return;
//                }
            //回写数据
            Object object = result.getContent();
            if (object != null) {
                response.setData(FastJsonUtils.toJson(object));
            }
            response.setStateCode(result.getResultCode());
            session.write(response);
        }
    }
}
